<template>
  <el-dialog title="选择图片" v-model="show" width="880px" :append-to-body="true" :close-on-click-modal="true">
    <div class='cropperBody'>
      <vue-picture-cropper :boxStyle="boxStyle" ref="cropper"
          :img="imgUrl"
          :options="options"
          @ready="ready"
      />
    </div>
    <div class='cropperBtn'>
      <el-button type='primary' size="small" v-on:click='onConfirm'>确认</el-button>
      <el-button v-on:click='show=false' size="small">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>

import VuePictureCropper from 'vue-picture-cropper'

export default {
  components: {
    VuePictureCropper
  },
  props: {
    width: {type: Number, default: 0},
    height: {type: Number, default: 0}
  },
  data() {
    return {
      show: false,
      boxStyle: {
        width: '100%',
        height: '100%',
        backgroundColor: '#f8f8f8',
        margin: 'auto'
      },
      options: {
        viewMode: 1,
        dragMode: 'crop',
        aspectRatio: null,
        preview: "",
      },
      imgUrl: null
    }
  },
  methods: {
    /**
     * 打开对话框
     */
    open(config = {}) {
      this.show = true;
      if(this.width && this.height) {
        this.options.aspectRatio = this.width / this.height
      }
      this.imgUrl = config.img
    },

    /**
     * 关闭对话框
     */
    close() {
      this.show = false;
    },

    onConfirm () {
      let a = this.$refs.cropper.getDataURL()
      let b = this.$refs.cropper.getBlob()
    }
  },
  watch: {
    show: function (val) {
      if (!val) {
        if (this.$refs.cropper.changeCropEnd) {
          this.$refs.cropper.changeCropEnd()
        }
      }
    }
  }
}
</script>
<style scoped lang="scss">
.cropperBody{
  width: 100%;
  height: 500px;
}
.cropperBtn{
  width: 100%;
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style>
